import webUrl from './url.js';
import $tools from './tools.js';
import Ajax1 from './Ajax11.js';

let needLoadingRequestCount = 0
let lang = uni.getStorageSync('languageMartin');
// var app = getApp();
var Ajax = new Object;
var setPublicKey = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCqeZgkdOGdSURNRiPtuWiRPbgKtwIfZyUrwwKq/w3iy8AMwXsAhvlGDoM1vpLcdU/FG/5revQSwBWAZNltPeM2fUdT0B4XlZ1b7vG9RO0smfKjyAIB9aWlg0ddUpl+EVRR3NPMxnc5o8jr/fJARSOGYB40B90dPprePDMPAreFLwIDAQAB'

import jsencrypt from '@/common/encryptlong/bin/jsencrypt.js'

global.endLoading = function() {
	if (needLoadingRequestCount <= 0) return
	needLoadingRequestCount--
	if (needLoadingRequestCount === 0) {
		uni.hideLoading();
	}
}
const ajax = (url, datas, successCallback, failCallBack, type = "POST",iftoken) => {
	// console.log(data)
	var key = Ajax1.createDesKey(16);
	let that = this;
	var data = {};
	data['data'] = datas;
	var  token = uni.getStorageSync('token') ? uni.getStorageSync('token') : '';
	if(url == '/api/user/login/userCreateWords' || url == '/api/user/login/userRegister' || url == '/api/user/login/userLogin'){
		data['data']['token'] = "";
	}else{
		data['data']['token'] = token;
	}
	let encryptor = new jsencrypt();
	encryptor.setPublicKey(setPublicKey);
	uni.request({
		url: webUrl.webUrl + url,
		// data: Ajax1.desEncrypt(Ajax1.toJSONString(data.data),key),//参数值
		data: Ajax1.desEncrypt(JSON.stringify(data.data),key),//参数值
		method: type || 'POST',
		dataType: 'json',
		async: false,
		header: {
			"content-type": "application/json",
			"key":Ajax1.rsaEncrypt(key)
		},
		success: (res) => {
			var code = res.data.code;
			if (res.data.success == true) {
				successCallback(res.data);
			}
			else if(res.data.success == false){
				// $tools.toast(res.data.msg);
				if(code == 'code_999990'){
					uni.removeStorageSync('token');
					uni.removeStorageSync('noticeStatus');
					if (getApp().globalData.is_flag) { 
						getApp().globalData.is_flag = false;
						console.log('没有登录');
						let token = uni.getStorageSync('token');
						if(!token){
							$tools.toast('登录已失效，请重新登录！！！');
							setTimeout(function() {
								$tools.redirectTo('/pages/operate/login');
							}, 1500)
							clearInterval();
							clearTimeout();  
						}
						setTimeout(() => {
							getApp().globalData.is_flag = true;
							console.log(getApp().globalData.is_flag);
						}, 1000)
					}
				}else if(code == 'code_999988'){
					console.log("抱歉，该账号已被封号，暂不能访问");
					$tools.toast(res.data.msg);
				}else{
					$tools.toast(res.data.msg);
					successCallback(res.data);
				}
			}
		},
		fail: (e) => {
			console.log(e);
			if(failCallBack){
				failCallBack();
			}
			uni.stopPullDownRefresh()
			// uni.showToast({
			// 	title: lang == 'cn' ?'连接失败,请稍后再试' :'Connection failed.try again later',
			// 	icon: "none",
			// 	duration: 2000
			// })
		}
	})
}
/**
 * RSA加密
 */
Ajax.rsaEncrypt = function(data){
    //加密
	if(data == null) return '';
    var encrypt = new jsencrypt();
    encrypt.setPublicKey(publicKey);
    var encryptData = encrypt.encryptLong(data);
    return encryptData;
}
// /**
//  * AES解密
//  */
// Ajax1.desDecrypt = function(data, aseKey){
//     //解密
// 	 var key = CryptoJS.enc.Utf8.parse(aseKey);//十六位十六进制数作为密钥
// 	 var decrypt = CryptoJS.AES.decrypt(data, key, {
// 	      mode: CryptoJS.mode.ECB,
// 	      padding: CryptoJS.pad.Pkcs7
// 	    });
// 	 var decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
// 	 return decryptedStr.toString();
// }
export default ajax